import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:go_router/go_router.dart';
import '../providers/comic_provider.dart';

class ComicReaderScreen extends ConsumerStatefulWidget {
  final String comicId;
  final String chapter;

  const ComicReaderScreen({
    super.key,
    required this.comicId,
    required this.chapter,
  });

  @override
  ConsumerState<ComicReaderScreen> createState() => _ComicReaderScreenState();
}

class _ComicReaderScreenState extends ConsumerState<ComicReaderScreen> {
  late PageController _pageController;
  int _currentPage = 0;
  bool _showUI = true;

  // Mock page URLs - in real app these would come from the chapter data
  late List<String> _pageUrls;

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
    _initializeMockPages();
  }

  void _initializeMockPages() {
    // Mock comic pages using the same images from the comic covers
    _pageUrls = [
      'https://ext.same-assets.com/2411567312/2108123692.png',
      'https://ext.same-assets.com/2411567312/3592246325.jpeg',
      'https://ext.same-assets.com/2411567312/3319491162.jpeg',
      'https://ext.same-assets.com/2411567312/2201258949.jpeg',
      'https://ext.same-assets.com/2411567312/1578322905.jpeg',
    ];
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  void _toggleUI() {
    setState(() {
      _showUI = !_showUI;
    });
  }

  void _nextPage() {
    if (_currentPage < _pageUrls.length - 1) {
      _pageController.nextPage(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }

  void _previousPage() {
    if (_currentPage > 0) {
      _pageController.previousPage(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }

  void _nextChapter() {
    final nextChapter = (int.parse(widget.chapter) + 1).toString();
    context.pushReplacement('/reader/${widget.comicId}/$nextChapter');
  }

  void _previousChapter() {
    final prevChapter = (int.parse(widget.chapter) - 1).toString();
    if (int.parse(widget.chapter) > 1) {
      context.pushReplacement('/reader/${widget.comicId}/$prevChapter');
    }
  }

  @override
  Widget build(BuildContext context) {
    final comics = ref.watch(comicsProvider);
    final comic = comics.firstWhere(
      (c) => c.id == widget.comicId,
      orElse: () => comics.first,
    );

    return Scaffold(
      backgroundColor: const Color(0xFF211839), // 主背景色
      body: Stack(
        children: [
          // Main content
          GestureDetector(
            onTap: _toggleUI,
            child: PageView.builder(
              controller: _pageController,
              onPageChanged: (index) {
                setState(() {
                  _currentPage = index;
                });
              },
              itemCount: _pageUrls.length,
              itemBuilder: (context, index) {
                return InteractiveViewer(
                  panEnabled: true,
                  boundaryMargin: const EdgeInsets.all(20),
                  minScale: 0.5,
                  maxScale: 3.0,
                  child: Center(
                    child: CachedNetworkImage(
                      imageUrl: _pageUrls[index],
                      fit: BoxFit.contain,
                      placeholder: (context, url) => const Center(
                        child: CircularProgressIndicator(
                          color: Color(0xFF6C5CE7), // 紫色加载指示器
                        ),
                      ),
                      errorWidget: (context, url, error) => const Center(
                        child: Icon(
                          Icons.error,
                          color: Color(0xFF8B7AA8), // 错误图标颜色
                          size: 50,
                        ),
                      ),
                    ),
                  ),
                );
              },
            ),
          ),

          // Navigation areas (invisible)
          Row(
            children: [
              // Left side - previous page
              Expanded(
                child: GestureDetector(
                  onTap: _previousPage,
                  child: Container(
                    color: Colors.transparent,
                  ),
                ),
              ),
              // Right side - next page
              Expanded(
                child: GestureDetector(
                  onTap: _nextPage,
                  child: Container(
                    color: Colors.transparent,
                  ),
                ),
              ),
            ],
          ),

          // Top UI
          if (_showUI)
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      const Color(0xFF211839).withOpacity(0.9), // 主背景色渐变
                      Colors.transparent,
                    ],
                  ),
                ),
                child: SafeArea(
                  child: AppBar(
                    backgroundColor: Colors.transparent,
                    foregroundColor: Colors.white, // 白色图标和文字
                    elevation: 0,
                    title: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          comic.title,
                          style: const TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                          ),
                        ),
                        Text(
                          'Chapter ${widget.chapter}',
                          style: const TextStyle(
                            fontSize: 12,
                            color: Color(0xFFB8B3C7), // 次要文字颜色
                          ),
                        ),
                      ],
                    ),
                    leading: IconButton(
                      icon: const Icon(Icons.arrow_back, color: Colors.white),
                      onPressed: () => context.pop(),
                    ),
                    actions: [
                      IconButton(
                        icon: const Icon(Icons.bookmark_border, color: Colors.white),
                        onPressed: () {
                          // Handle bookmark
                        },
                      ),
                      IconButton(
                        icon: const Icon(Icons.more_vert, color: Colors.white),
                        onPressed: () {
                          // Handle more options
                        },
                      ),
                    ],
                  ),
                ),
              ),
            ),

          // Bottom UI
          if (_showUI)
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.bottomCenter,
                    end: Alignment.topCenter,
                    colors: [
                      const Color(0xFF211839).withOpacity(0.95), // 主背景色渐变
                      Colors.transparent,
                    ],
                  ),
                ),
                child: SafeArea(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      // Progress slider
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 20),
                        child: Row(
                          children: [
                            Text(
                              '${_currentPage + 1}',
                              style: const TextStyle(
                                color: Colors.white,
                                fontSize: 12,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                            Expanded(
                              child: Slider(
                                value: _currentPage.toDouble(),
                                min: 0,
                                max: (_pageUrls.length - 1).toDouble(),
                                divisions: _pageUrls.length - 1,
                                activeColor: const Color(0xFF6C5CE7), // 紫色滑块
                                inactiveColor: const Color(0xFF3D2F5A), // 非活跃滑块颜色
                                thumbColor: const Color(0xFF6C5CE7),
                                onChanged: (value) {
                                  _pageController.animateToPage(
                                    value.round(),
                                    duration: const Duration(milliseconds: 300),
                                    curve: Curves.easeInOut,
                                  );
                                },
                              ),
                            ),
                            Text(
                              '${_pageUrls.length}',
                              style: const TextStyle(
                                color: Colors.white,
                                fontSize: 12,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                      ),

                      // Navigation buttons
                      Padding(
                        padding: const EdgeInsets.all(16),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            ElevatedButton.icon(
                              onPressed: int.parse(widget.chapter) > 1
                                  ? _previousChapter
                                  : null,
                              icon: const Icon(Icons.skip_previous),
                              label: const Text('Prev Chapter'),
                              style: ElevatedButton.styleFrom(
                                backgroundColor: const Color(0xFF2A1F3D), // 次级背景色
                                foregroundColor: Colors.white,
                                disabledBackgroundColor: const Color(0xFF3D2F5A).withOpacity(0.5),
                                disabledForegroundColor: const Color(0xFF8B7AA8),
                                elevation: 4,
                                shadowColor: Colors.black.withOpacity(0.3),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(8),
                                  side: BorderSide(
                                    color: const Color(0xFF3D2F5A),
                                    width: 1,
                                  ),
                                ),
                              ),
                            ),
                            ElevatedButton.icon(
                              onPressed: _nextChapter,
                              icon: const Icon(Icons.skip_next),
                              label: const Text('Next Chapter'),
                              style: ElevatedButton.styleFrom(
                                backgroundColor: const Color(0xFF6C5CE7), // 紫色按钮
                                foregroundColor: Colors.white,
                                elevation: 4,
                                shadowColor: const Color(0xFF6C5CE7).withOpacity(0.3),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(8),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }
}
